<?php

namespace App\Repository\Commit;

use App\Models\DistClass as model;
use Illuminate\Support\Facades\Cache;
use App\Repository\RoleRepository;
use Illuminate\Support\Facades\DB;
use App\Repository\BaseRepository;
use App\Repository\Admin\AdminUsersRepository;

class DistClassRepository extends  BaseRepository
{
  private $model;
  private $userModel;
  public function __construct(model $model)
  {
    $this->model = $model;
    $this->userModel = new AdminUsersRepository();
    parent::__construct();
  }
  //列表
  public function index($where)
  {
    $cron = $where;
    $cron['order'] = ['orderby' => 'dept_id', 'orderdir' => 'desc'];
    // $cron['where'] = $where;
    // var_dump($cron,111111111);
    $data = $this->search($this->model, $cron, 1, 9000000);
    if (!empty($data['data'])) {
      $data['data'] = usfirstArr($data['data']);
    }
    return $data;
  }
  //添加
  public function add($data)
  {
    //必填 字段
    $mustField = [
      'dept_name',
    ];
    $optionalFields = $this->model->getTableField();
    $msgField = [
      'dept_name' => '名称不能为空'
    ];
    $reparams = $data->all();
    // var_dump($reparams,777777777777);
    // var_dump($data,555555555);
    if(!empty($data['dist_id'])){
      $data['dist_id'] = implode(',',$data['dist_id']);
    }
    // var_dump($data,666666666);
    $insertData  = $this->getRealData($data, $mustField, $optionalFields, $msgField);
    if (!empty($insertData) && is_string($insertData)) {
      //返回错误参数
      return $this->returnMsg(
        2,
        $insertData
      );
    }
    if(!empty($insertData['dist_id']) && !is_array($insertData['dist_id'])){
      $insertData['dist_id'] = explode(',',$insertData['dist_id']);
    }
    // var_dump($insertData['dist_id'],5555555555555);
    //查询父类的参数
    $resP = $this->model->where(['dept_id' => $insertData['parent_id']])->first();
    if (empty($resP)) {
      return $this->returnMsg(100, '未查询到上级');
    }
    // 负责人
    if(!empty($insertData['leader'])){
      $userArr = $this->userModel->oneSel(['id'=>$insertData['leader']]);
      if(!$userArr){
        return $this->returnMsg(103,'未查询到用户信息');
      }
      $insertData['leader_name'] = $userArr['userName'];
    }
    // 代理
    $isTrue = true;
    if(!empty($insertData['dist_id']) && is_array($insertData['dist_id'])){
      $distStr = ',';
      $distNameStr = ',';
      $isTrue = false;
      $distUser = DB::table('supplier')->whereIn('shop_id',$insertData['dist_id'])->where('supplier_id',$data->user->shop_id)->get();
      // var_dump($distUser);
      if(!$distUser){
        return $this->returnMsg(1050,'代理信息未查询到');
      }
      foreach($distUser as $key => $v){
        $distStr .= $v->shop_id.',';
        $distNameStr .= $v->name.',';
      }
      $insertData['dist_id'] = $distStr;
      $insertData['dist_name'] = $distNameStr;
    }
    if(!empty($insertData['dist_id']) && is_string($insertData['dist_id']) && $isTrue){
      $distStr = ',';
      $distNameStr = ',';
      $distUser = DB::table('supplier')->where(['shop_id'=>$insertData['dist_id'],'supplier_id'=>$data->user->shop_id])->first();
      // var_dump($distUser);
      if(!$distUser){
        return $this->returnMsg(105,'代理信息未查询到');
      }
      $distStr .= $distUser->shop_id.',';
      $distNameStr .= $distUser->name.',';
      $insertData['dist_id'] = $distStr;
      $insertData['dist_name'] = $distNameStr;
    }
    $insertData['ancestors'] = trim($resP->ancestors,'.') . '.' . $insertData['parent_id'] . '.';
    if(!empty($insertData['ancestors'])){
      // 批量更改 上游的代理信息
      $ancest = explode('.',$insertData['ancestors']);
      foreach($ancest as $key => $v){
        if(!empty($v)){
          $where = ['dept_id'=>$v];
          $updatePar = [
            'dist_id' => $insertData['dist_id'],
            // 'dist_name' => $insertData['dist_name'],
          ];
          $this->edit($where,$updatePar,false,1);
        }
      }
    }
    $insertData['order_num'] = 0;
    
    $insertData['shop_id'] = $data->user->shop_id;
    $insertData['create_time'] = date('Y-m-d H:i:s');
    $insertData['create_by'] = $data->user->id;

    $res = $this->model->insert($insertData);
    if ($res) {
      return $this->returnMsg(200, '添加成功');
    }
    return $this->returnMsg(1, '添加失败');
  }
  //删除
  public function del($where)
  {
    $flag = true;
    $msg = '未知错误';
    $code = 1;
    if (empty($where)) {
      $flag = false;
      $msg = '删除条件不能为空';
      $code = 2;
    }
    if ($flag) {
      $res = $this->model->where($where)->get();
      if (!$res) {
        $flag = false;
        $msg = '未查询到数据';
        $code = 3;
      }
    }
    if ($flag) {
      $del = $this->model->where($where)->delete();
      if ($del) {
        $msg = '删除成功';
        $code = 200;
      }
    }
    return $this->returnMsg($code, $msg);
  }
  //修改
  public function edit($where, $data, $isMust = false,$isTrpe=0)
  {
    if (empty($where)) {
      return $this->returnMsg(1, '条件不能为空');
    }
    if (empty($data)) {
      return $this->returnMsg(2, '修改参数不能为空');
    }
    if(!empty($data['dist_id']) && is_array($data['dist_id'])){
      $data['dist_id'] = implode(',',$data['dist_id']);
    }
    //过滤字段
    $optionalFields = $this->model->getTableField();
    $field  = $this->getRealData($data, [], $optionalFields, []);
    if(!empty($field['dist_id']) && !is_array($field['dist_id'])){
      $field['dist_id'] = explode(',',$field['dist_id']);
    }
    $isTrue = $this->model->where($where)->first();
    if(!$isTrue){
      return $this->returnMsg(3,'未查询到信息');
    }
    if (!empty($field['parent_id'])) {
      $resP = $this->model->where(['dept_id' => $field['parent_id']])->first();
      if (empty($resP)) {
        return $this->returnMsg(100, '未查询到上级');
      }
      $field['ancestors'] = trim($resP->ancestors,'.') . '.' . $field['parent_id'] . '.';
    }
    //先查询是否存在
    // 负责人
    if(!empty($field['leader'])){
      $userArr = $this->userModel->oneSel(['id'=>$field['leader']]);
      if(!$userArr){
        return $this->returnMsg(103,'未查询到用户信息');
      }
      $field['leader_name'] = $userArr['userName'];
    }
    // 代理
    if(!empty($field['dist_id']) && !empty($isTrpe) && $isTrpe == 1){
      $a1 = $field['dist_id'];
      if(is_string($field['dist_id'])){
        $a1 = explode(',',trim($field['dist_id'],','));
      }
      
      $a2 = [];
      if(!empty($isTrue->dist_id)){
        $a2 = explode(',',trim($isTrue->dist_id,','));
      }
      
      $field['dist_id'] = array_merge($a1,$a2);
      // $field['dist_name'] = array_merge(explode(',',$field['dist_name']),explode(',',$isTrue->dist_name));
    }
    if(!empty($field['dist_id']) && is_array($field['dist_id'])){
      $distStr = ',';
      $distNameStr = ',';
      $distUser = DB::table('supplier')->whereIn('shop_id',$field['dist_id'])->where('supplier_id',$isTrue->shop_id)->get();
      if(!$distUser){
        return $this->returnMsg(105,'代理信息未查询到');
      }
      foreach($distUser as $key => $v){
        $distStr .= $v->shop_id.',';
        $distNameStr .= $v->name.',';
      }
      $field['dist_id'] = $distStr;
      $field['dist_name'] = $distNameStr;
    }
    if(!empty($insertData['dist_id']) && is_string($insertData['dist_id'])){
      $distStr = ',';
      $distNameStr = ',';
      $distUser = DB::table('supplier')->where(['shop_id'=>$insertData['dist_id'],'supplier_id'=>$data->user->shop_id])->first();
      // var_dump($distUser);
      if(!$distUser){
        return $this->returnMsg(105,'代理信息未查询到');
      }
      $distStr .= $distUser->shop_id.',';
      $distNameStr .= $distUser->name.',';
      $insertData['dist_id'] = $distStr;
      $insertData['dist_name'] = $distNameStr;
    }
    
    if(!empty($field['ancestors']) && !empty($field['dist_id']) && empty($isTrpe)){
      // 批量更改 上游的代理信息
      $ancest = explode('.',$field['ancestors']);
      foreach($ancest as $key => $v){
        if(!empty($v) && $v != 1){
          $whereAA = [
            'dept_id'=>$v,
            'shop_id' => $isTrue->shop_id
          ];
          $updatePar = [
            'dist_id' => $field['dist_id'],
            // 'dist_name' => $field['dist_name'],
          ];
          // var_dump($updatePar,666666);
          $this->edit($whereAA,$updatePar,false,1);
        }
      }
    }
    // var_dump($field,444444444444);
    // $res = '';
    $res = $this->model->where($where)->update($field);
    if ($isMust && $res) {
      return $this->returnMsg(200, '修改成功');
    }
    if (!$isMust) {
      return $this->returnMsg(200, '修改成功');
    }
    return $this->returnMsg(3, '请重新修改');
  }
  //列表查询
  public function lists($where = [], $page = 1, $limit = 10)
  {
    $res = $this->search($this->model, $where, $page, $limit);

    return $res;
  }
  public function getOne($where)
  {
    return $this->model->where($where)->first();
  }
  public function treeSelect($where = [], $field = [], $shop_id = '')
  {
    if (empty($field)) {
      $field = ['dept_id as id', 'dept_name as label'];
    }
    $return = $this->model->where($where)->select($field)->get();
    if (!empty($return)) {
      foreach ($return as $key => $v) {
        $whereTwo = [
          'parent_id' => $v->id,
          'shop_id' => $shop_id
        ];
        $v['children'] = $this->treeSelect($whereTwo, [], $shop_id);
      }
    }
    return $return;
  }
}
